<template>
  <div class="namelist">
    <div class="measure">
      <div class="measure-name">
        <div>陪练</div>
        <div></div>
      </div>
    </div>

    <div class="chat-container">
      <div class="chat-messages" ref="chatMessagesRef">
        <div
          v-for="(message, index) in chatMessages"
          :key="index"
          :class="{
            'user-message': message.isUser,
            'ai-message': !message.isUser,
          }"
        >
          <div class="message-wrapper">
            <img
              v-if="!message.isUser"
              src="/img/AI.png"
              alt="AI 头像"
              class="avatar"
            />
            <!-- <icon-caret-right   v-if="!message.isUser" /> -->
            <icon-caret-left class="iconist" v-if="!message.isUser" />
            <text :class="message.isUser ? 'message-content' : 'message-left'">
              {{ message.content }}
            </text>
            <!-- <icon-caret-left  v-if="message.isUser"/> -->
            <icon-caret-right class="iconright" v-if="message.isUser" />
            <img
              v-if="message.isUser"
              src="/img/xuexi.png"
              alt="用户头像"
              class="avatarlist"
            />
          </div>
        </div>
      </div>
      <div class="chat-input">
        <a-textarea v-model="userInput" :placeholder="placeholder" />

        <a-button class="button" @click="sendMessage" type="primary"
          >发送</a-button
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref, watch, onUnmounted, reactive } from "vue";
import { EventSourcePolyfill } from "event-source-polyfill";
import { AichatController } from "@/api/accmpany";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
// const router = useRouter();
const subjectID = userStore.$state.subjectID;
interface ChatMessage {
  content: string;
  isUser: boolean;
}

interface SSEEventResult {
  time?: string;
  content?: string;
  type?: "content" | "conversation";
}

// 响应式数据
const chatMessages = ref<ChatMessage[]>([]);
const userInput = ref<string>("");
const chatMessagesRef = ref<HTMLElement | null>(null);
const isLoading = ref(false);
const conversationId = ref<string>("");
const eventSource = ref<EventSourcePolyfill | null>(null);
const placeholder = ref();
// 获取用户ID
const getUserId = () => {
  try {
    const permission = JSON.parse(localStorage.getItem("permission") || "{}");
    return permission.UserID || "";
  } catch {
    return "";
  }
};
const subjectIDname = () => {
  try {
    const permission = JSON.parse(localStorage.getItem("permission") || "{}");
    const targetItem = permission.gradeList.find(
      (item: any) => item.SubjectID == froms.subjectId
    );
    if (targetItem) {
      return targetItem.SubjectName;
    }
  } catch {
    return "";
  }
};

// 发送消息处理
const sendMessage = () => {
  const input = userInput.value.trim();
  if (!input || isLoading.value) return;

  // 添加用户消息
  chatMessages.value.push({
    content: input,
    isUser: true,
  });

  // 清空输入框
  userInput.value = "";

  // 调用SSE连接
  connectSSE(input);
};

// 建立SSE连接
const connectSSE = (message: string) => {
  isLoading.value = true;

  // 关闭已有连接
  if (eventSource.value) {
    eventSource.value.close();
  }

  // 添加AI消息占位
  chatMessages.value.push({
    content: "",
    isUser: false,
  });

  // 处理特殊字符
  const encodedContent = encodeURIComponent(
    message.replace(/\+/g, "{[$add$]}")
  );
  const userId = getUserId();
  // const SubjectName = subjectIDname()
  // console.log(SubjectName,'?')
  const url = `/aichat/stream-chat/chat.php?question=${encodedContent}&conversationId=${conversationId.value}&userid=${userId}&subjectID=${froms.subjectId}`;

  eventSource.value = new EventSourcePolyfill(url);
  let aiResponse = "";

  eventSource.value.onmessage = (event: MessageEvent) => {
    const result: SSEEventResult = JSON.parse(event.data);

    if (result.time && result.content) {
      if (result.type === "content") {
        // 更新最后一条AI消息内容
        aiResponse += result.content;
        const lastMessage = chatMessages.value[chatMessages.value.length - 1];
        if (!lastMessage.isUser) {
          lastMessage.content = aiResponse;
        }
      } else if (result.type === "conversation") {
        conversationId.value = result.content;
      }
    }
  };

  eventSource.value.onerror = () => {
    isLoading.value = false;
    if (eventSource.value) {
      eventSource.value.close();
    }
  };

  eventSource.value.onclose = () => {
    isLoading.value = false;
  };
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
};

// 监听消息变化自动滚动
watch(chatMessages, scrollToBottom, { deep: true });

const froms = reactive({
  subjectId: "",
});

const controller = () => {
  AichatController(froms).then((res: any) => {
    // res.welcome;
    placeholder.value = res.placeholder;
    if (res.welcome) {
      // 添加欢迎消息到 AI 消息列表
      chatMessages.value.push({
        content: res.welcome,
        isUser: false,
      });
    }
  });
};

watch(
  () => userStore.$state.subjectID,
  async (newValue, oldValue) => {
    try {
      if (userStore.$state.subjectID) {
        froms.subjectId = userStore.$state.subjectID;

        controller();
      }
    } catch (error) {
      console.error("获取数据出错:", error);
    }
  },
  { immediate: true }
);
onMounted(() => {
  if (subjectID) {
    froms.subjectId = subjectID;
    // controller();
  }
  scrollToBottom();
});

onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close();
  }
});
</script>

<style lang="less" scoped>
.namelist {
  width: 100%;
  height: 100%;
}
.measure {
  height: 70px;
  background: #0075ff;
  border-radius: 8px;
  border-top: 1px solid #0075ff;
}
.measure-name {
  line-height: 70px;
  padding: 0 24px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  border-bottom: 1px solid #ededed;
  justify-content: space-between;
}
.chat-container {
  border-radius: 5px;
  // box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.iconist {
  // margin-top: -5px;
  margin-right: -6px;
  color: #f7fbff;
}
.iconright {
  // margin-top: 5px;
  margin-left: -6px;
  color: #007bff;
  // background: #F7FBFF;
}
.chat-header {
  background-color: #f4f4f4;
  // padding: 10px;
  text-align: center;
}

.chat-messages {
  height: 50vh;
  background-color: #fff;
  overflow-y: auto;
  // padding: 10px;
}

.chat-messages div {
  margin-bottom: 10px;
  // padding: 10px;
  border-radius: 5px;
}

.user-message {
  // background-color: #e1f5fe;
  position: relative;
  text-align: right;
  // text-align-last: left; /* 换行后的文本靠左显示 */
  // font-size: 30px;
}

.chat-input {
  display: flex;
  position: relative;
  height: 20vh;
  padding: 10px;
  z-index: 0;
}
.button {
  position: absolute;
  bottom: 1vw;
  right: 1vw;
  z-index: 1;
}
:deep .arco-textarea {
  background-color: #f7fbff;
}
.chat-input input {
  flex: 1;
  padding: 5px;
}

.chat-input button {
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 2vw;
  height: 2vw;
  border-radius: 1vw;
  margin-right: 0.3vw;
}
.avatarlist {
  width: 2vw;
  height: 2vw;
  border-radius: 1vw;
  margin-left: 0.3vw;
}
.message-content {
  padding: 0.5vw;
  max-width: 50vw;
  display: inline-block;
  border-radius: 0.5vw;
  background-color: #0075ff;
  color: #ffffff;
  word-wrap: break-word;
  word-break: break-all;
}
.message-left {
  padding: 0.5vw;
  display: inline-block;
  max-width: 50vw;
  border-radius: 0.5vw;
  background: #f7fbff;
  color: #0075ff;
}
@media (max-width: 768px) {
  .button {
    position: absolute;
    bottom: 3vw;
    right: 3vw;
    z-index: 1;
  }
  .avatarlist {
    width: 4vw;
    height: 4vw;
    border-radius: 2vw;
    margin-left: 0.3vw;
  }
  .avatar {
    width: 4vw;
    height: 4vw;
    border-radius: 2vw;
    margin-right: 0.3vw;
  }
}
</style>
